package com.ruoyi.auth.listener;

import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    RedisService redisService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 使用该方法监听 ,当我们的key失效的时候执行改方法
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expirationKey = message.toString();
        String username = SecurityUtils.getUsername();
        String redisKey = username +Constants.IS_LOGIN;
        if (expirationKey.equals(redisKey)){
            redisService.deleteObject(redisKey);
            Claims claims = JwtUtils.parseToken(username);
            String tokenKey = (String) claims.get("access_token");
            tokenKey = CacheConstants.LOGIN_TOKEN_KEY+tokenKey;
            redisService.deleteObject(tokenKey);
        }
    }
}
